package com.avcdata.national.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.avcdata.aoscustommade.R;
import com.avcdata.aoscustommade.activity.Login_Activity;
import com.avcdata.aoscustommade.adapter.MyWheelAdapter;
import com.avcdata.aoscustommade.main.BaseFragment;
import com.avcdata.aoscustommade.utils.AvcConstants;
import com.avcdata.aoscustommade.utils.SharedPreferencesUtils;
import com.avcdata.aoscustommade.utils.TextUitl;
import com.avcdata.national.activity.ScaleBasisRatioActivity;
import com.avcdata.national.adapter.ModelAdapter;
import com.avcdata.national.module.BestModel;
import com.avcdata.national.module.ModelListViewInfo;
import com.avcdata.national.network.BaseLog;
import com.avcdata.national.network.JsonRunnable;
import com.avcdata.national.network.ThreadPoolUtils;
import com.avcdata.national.utils.MyBaseFragment;
import com.google.gson.Gson;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.wx.wheelview.widget.WheelView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.avcdata.aoscustommade.R.id.dialog_cancel;
import static com.avcdata.aoscustommade.utils.AvcConstants.URL_MarketAvg;
import static com.avcdata.aoscustommade.utils.AvcConstants.URL_Model_best;
import static com.avcdata.aoscustommade.utils.AvcConstants.URL_Model_new;

/**
 * Created by Lucasey on 2017/8/22.
 */

public class HotSaleFragment extends MyBaseFragment {
    @ViewInject(R.id.sale_type)
    private LinearLayout sale_type;
    @ViewInject(R.id.sale_text)
    private TextView sale_text;
    @ViewInject(R.id.line_type)
    private LinearLayout line_type;
    @ViewInject(R.id.line_text)
    private TextView line_text;
    @ViewInject(R.id.week_type)
    private LinearLayout week_type;
    @ViewInject(R.id.week_text)
    private TextView week_text;
    @ViewInject(R.id.proportion_type)
    private LinearLayout proportion_type;
    @ViewInject(R.id.proportion_text)
    private TextView proportion_text;

    @ViewInject(R.id.lv)
    private ListView lv;

    private ModelAdapter adapter;

    private List<ModelListViewInfo> list = new ArrayList<>();

    private String measureString = "online";
    private String weekString = "current";
    private String saleString = "amount";
    private String propString = "new";
    private String measureStringTemp = "";
    private String weekStringTemp = "";
    private String saleStringTemp = "";
    private String propStringTemp = "";

    private LinearLayout loading;

    private Dialog dialog;
    private ArrayList<String> dataMeasure;
    private ArrayList<String> weeks;
    private ArrayList<String> sales;
    private ArrayList<String> props;

    private ScaleBasisRatioActivity scaleBasisRatioActivity;

    private View v;

    @Override
    protected View onLayoutView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_national_hotsale, container, false);
    }

    @Override
    protected void initView(View container, Bundle savedInstanceState) {
        ViewUtils.inject(this, container);
        week_type.setOnClickListener(this);
        line_type.setOnClickListener(this);
        sale_type.setOnClickListener(this);
        proportion_type.setOnClickListener(this);
        scaleBasisRatioActivity = (ScaleBasisRatioActivity) getActivity();
        loading = scaleBasisRatioActivity.getLoading();
        initOnCreate();
    }

    private void initOnCreate() {
        loading.setVisibility(View.GONE);
        dataMeasure = new ArrayList<>();
        dataMeasure.add("线上");
        dataMeasure.add("线下");
        props = new ArrayList<>();
        props.add("新品型号");
        props.add("畅销型号");
        weeks = new ArrayList<>();
        weeks.add("当前周");
        weeks.add("近四周");
        weeks.add("近八周");
        weeks.add("本年累计");
        sales = new ArrayList<>();
        sales.add("销量");
        sales.add("销额");
        //设置线上线下方式
        if (new SharedPreferencesUtils(getActivity()).getLineType() == 1) {
            line_text.setText("线上");
            measureString = "online";
        } else {
            line_text.setText("线下");
            measureString = "offline";
        }
        //设置同比环比
        proportion_text.setText("畅销型号");
        propString = "best";
        //设置周度
        switch (new SharedPreferencesUtils(getActivity()).getWeekType()) {
            case "近四周":
                week_text.setText("近四周");
                weekString = "fourWeek";
                break;
            case "近八周":
                week_text.setText("近八周");
                weekString = "eightWeek";
                break;
            case "本年累计":
                week_text.setText("本年累计");
                weekString = "year";
                break;
            case "当前周":
                week_text.setText("当前周");
                weekString = "current";
                break;
            default:
                week_text.setText("当前周");
                weekString = "current";
                break;
        }
        //设置销量销额方式
        if (new SharedPreferencesUtils(getActivity()).getSaleType() == 1) {
            sale_text.setText("销量");
            saleString = "volume";
        } else {
            sale_text.setText("销额");
            saleString = "amount";
        }

        adapter = new ModelAdapter(list,getActivity());
        adapter.setIsNew(false);
        lv.setAdapter(adapter);

        getBrandScaleBasisRatio();
    }


    @Override
    protected void onclickEvent(View view) {
        switch (view.getId()) {
            case R.id.proportion_type:
                showDialogSelect(4);
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
                break;
            case R.id.sale_type:
                showDialogSelect(1);
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
                break;
            case R.id.line_type:
                showDialogSelect(3);
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
                break;
            case R.id.week_type:
                showDialogSelect(2);
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
                break;
            default:
                break;
        }
    }

    /***
     * 获取选择的索引
     * @param dataTemp
     * @param stringTemp
     * @return
     */
    private int getSelectPosition(ArrayList<String> dataTemp, String stringTemp) {
        int temp = 0;
        for (int i = 0; i < dataTemp.size(); i++) {
            if (dataTemp.get(i).equals(stringTemp)) {
                temp = i;
            }
        }
        return temp;
    }


    /***
     *单选dialog
     * @param dialogNum 3-线上线下/2-最新周···
     */
    private void showDialogSelect(final int dialogNum) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_single, null);
        dialog = new Dialog(getActivity(), R.style.DialogBlack);
        Window window = dialog.getWindow();
        window.setContentView(view);
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        window.setGravity(Gravity.CENTER);

        final TextView dialog_title1 = (TextView) view.findViewById(R.id.dialog_title1);
        TextView dialog_title2 = (TextView) view.findViewById(R.id.dialog_title2);
        final WheelView wheelview_single1 = (WheelView) view.findViewById(R.id.wheelview_single1);
        final WheelView wheelview_single2 = (WheelView) view.findViewById(R.id.wheelview_single2);
        dialog_title2.setVisibility(View.GONE);
        wheelview_single2.setVisibility(View.GONE);
        wheelview_single1.setSkin(WheelView.Skin.None);
        WheelView.WheelViewStyle style = new WheelView.WheelViewStyle();
        style.selectedTextColor = Color.RED;
        style.selectedTextSize = 20;
        style.textColor = Color.BLACK;
        wheelview_single1.setStyle(style);
        wheelview_single1.setLoop(false);
        wheelview_single1.setWheelClickable(false);
        switch (dialogNum) {
            case 1:
                dialog_title1.setText("选择销量销额");
                wheelview_single1.setWheelData(sales);
                wheelview_single1.setSelection(getSelectPosition(sales, saleStringTemp));
                wheelview_single1.setWheelSize(3);
                wheelview_single1.setWheelAdapter(new MyWheelAdapter(getActivity()));
                break;
            case 2:
                dialog_title1.setText("选择周度时长");
                wheelview_single1.setWheelData(weeks);
                wheelview_single1.setSelection(getSelectPosition(weeks, weekStringTemp));
                wheelview_single1.setWheelSize(3);
                wheelview_single1.setWheelAdapter(new MyWheelAdapter(getActivity()));
                break;
            case 3:
                dialog_title1.setText("选择销售状况");
                wheelview_single1.setWheelData(dataMeasure);
                wheelview_single1.setSelection(getSelectPosition(dataMeasure, measureStringTemp));
                wheelview_single1.setWheelSize(3);
                wheelview_single1.setWheelAdapter(new MyWheelAdapter(getActivity()));
                break;
            case 4:
                dialog_title1.setText("选择同比环比");
                wheelview_single1.setWheelData(props);
                wheelview_single1.setSelection(getSelectPosition(props, propStringTemp));
                wheelview_single1.setWheelSize(3);
                wheelview_single1.setWheelAdapter(new MyWheelAdapter(getActivity()));
                break;
            default:
                break;
        }

        view.findViewById(dialog_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });

        view.findViewById(R.id.dialog_ensure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (dialogNum) {
                    case 1:
                        saleStringTemp = sales.get(wheelview_single1.getCurrentPosition());
                        sale_text.setText(saleStringTemp);
                        if (sales.get(wheelview_single1.getCurrentPosition()).equals("销量")) {
                            saleString = "volume";
                            sale_text.setText("销量");
                            new SharedPreferencesUtils(getActivity()).setSaleType(1);
                        } else {
                            saleString = "amount";
                            sale_text.setText("销额");
                            new SharedPreferencesUtils(getActivity()).setSaleType(2);
                        }
                        break;
                    case 2:
                        weekStringTemp = weeks.get(wheelview_single1.getCurrentPosition());
                        week_text.setText(weekString);
                        switch (weekStringTemp) {
                            case "近四周":
                                week_text.setText("近四周");
                                weekString = "fourWeek";
                                new SharedPreferencesUtils(getActivity()).setWeekType("近四周");
                                break;
                            case "近八周":
                                week_text.setText("近八周");
                                weekString = "eightWeek";
                                new SharedPreferencesUtils(getActivity()).setWeekType("近八周");
                                break;
                            case "本年累计":
                                week_text.setText("本年累计");
                                weekString = "year";
                                new SharedPreferencesUtils(getActivity()).setWeekType("本年累计");
                                break;
                            case "当前周":
                                week_text.setText("当前周");
                                weekString = "current";
                                new SharedPreferencesUtils(getActivity()).setWeekType("当前周");
                                break;
                            default:
                                week_text.setText("当前周");
                                weekString = "current";
                                new SharedPreferencesUtils(getActivity()).setWeekType("当前周");
                                break;
                        }
                        break;
                    case 3:
                        measureStringTemp = dataMeasure.get(wheelview_single1.getCurrentPosition());
                        line_text.setText(measureString);
                        if (dataMeasure.get(wheelview_single1.getCurrentPosition()).equals("线上")) {
                            measureString = "online";
                            line_text.setText("线上");
                            new SharedPreferencesUtils(getActivity()).setLineType(1);
                        } else {
                            measureString = "offline";
                            line_text.setText("线下");
                            new SharedPreferencesUtils(getActivity()).setLineType(2);
                        }
                        break;
                    case 4:
                        propStringTemp = props.get(wheelview_single1.getCurrentPosition());
                        proportion_text.setText(propString);
                        if (props.get(wheelview_single1.getCurrentPosition()).equals("畅销型号")) {
                            propString = "best";
                            proportion_text.setText("畅销型号");
                            new SharedPreferencesUtils(getActivity()).setRatioType(1);
                        } else {
                            propString = "new";
                            proportion_text.setText("新品型号");
                            new SharedPreferencesUtils(getActivity()).setRatioType(2);
                        }
                        break;
                }
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                getBrandScaleBasisRatio();
            }
        });
    }

    /**
     * 获取上半部分规模同比
     * api/scale/brandScaleBasisRatio
     */
    private void getBrandScaleBasisRatio() {
        loading.setVisibility(View.VISIBLE);
        String url = "";
        if(propString.equals("new")){
            url = AvcConstants.URLHeaderBase + URL_Model_new;
            adapter.setIsNew(true);
        }else{
            adapter.setIsNew(false);
            url = AvcConstants.URLHeaderBase + URL_Model_best;
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("salesType", saleString);
        map.put("linesType", measureString);
        map.put("timeType", weekString);
        map.put("category", scaleBasisRatioActivity.getCategory());
        map.put("lastWeek", new SharedPreferencesUtils(getActivity()).getNewWeek());
        ThreadPoolUtils.execute(new JsonRunnable(getActivity(), "HTTPGET", url, handler, map, 1));
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case -1:
                    loading.setVisibility(View.GONE);
                    break;
                case 1:
                    loading.setVisibility(View.GONE);
                    BestModel bm = new Gson().fromJson(msg.obj.toString(),BestModel.class);
                    list.clear();
                    for(BestModel.ReturnValueBean svb : bm.getReturnValue()){
                        ModelListViewInfo mlvi = new ModelListViewInfo();
                        mlvi.setBrand(svb.getBrand());
                        mlvi.setModel(svb.getModel());
                        if(saleString.equals("amount")){
                            mlvi.setMarketShare(svb.getAmountMarketShare());
                            mlvi.setMarketShareLinkRelativeRatio(svb.getAmountMarketShareLinkRelativeRatio());
                        }else{
                            mlvi.setMarketShare(svb.getVolumeMarketShare());
                            mlvi.setMarketShareLinkRelativeRatio(svb.getVolumeMarketShareLinkRelativeRatio());
                        }
                        mlvi.setAvgPrice(svb.getAvgPrice());
                        mlvi.setAvgPriceRatio(svb.getAvgPriceLinkRelativeRatio());
                        mlvi.setSpec(svb.getProductTechs());
                        list.add(mlvi);
                    }
                    adapter.notifyDataSetChanged();
                    if(weekString.equals("current")){
                        week_text.setText(new SharedPreferencesUtils(getActivity()).getNewWeek());
                    }
                    break;
                case -22:
                    loading.setVisibility(View.GONE);
                    Intent intent = new Intent ();
                    intent.setClass ( getActivity (), Login_Activity.class );
                    intent.setFlags ( Intent.FLAG_ACTIVITY_CLEAR_TASK );  //注意本行的FLAG设置
                    getActivity ().finish ();
                    startActivity ( intent );
                    break;
                default:
                    break;
            }
        }
    };

}
